import { Floor, SearchRet } from '../../../shared/model/defination';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { SortType, FloorSearchCriteria } from '../../../entities/entities';
import { AuthService } from '../../../services/auth-service';
// import { SearchRet } from '../../../services/core/base-generic-service';
import { FloorService } from '../../../services/floor-service';
import { Router, ActivatedRoute, Params, Route } from '@angular/router';
import { MdlDialogService, MdlSnackbarService } from '@angular-mdl/core';

@Component({
	selector: 'app-index',
	templateUrl: './index.component.html',
	styleUrls: ['./index.component.scss'],
	providers: [FloorService, MdlDialogService, MdlSnackbarService]
})
export class IndexComponent implements OnInit {


	constructor(
		private _route: ActivatedRoute,
		private _router: Router,
		private _floorService: FloorService,
		private _dialogService: MdlDialogService,
		private _snackBarService: MdlSnackbarService
	) { }

	public get BuildingId() {
		return +this._route.snapshot.params['buildingId'];
	}
	@ViewChild('confirmAlert')
	public confirmAlert;
	public count: number = 0;
	public offset: number = 0;
	public limit: number = 10;
	public deleteId: number = 0;
	public isPageLoading: boolean = false;
	public rows = [];
	public pagerMessage = {
		emptyMessage: '没有数据',
		totalMessage: '总计'
	}
	public columns = [
		{ name: 'Id', prop: 'id' },
		{ name: '序号', prop: 'index' },
		{ name: '别名', prop: 'name' },
		{ name: '所属楼号', prop: 'building' }
	];
	async ngOnInit() {
		this.page(this.offset, this.limit);
	}
	async page(offset, limit) {
		this.isPageLoading = true;
		let criteria: FloorSearchCriteria = FloorSearchCriteria.fromJS({
			// BuildingId: this.BuildingId,
			IsDeleted: false,
			PageSize: this.limit,
			PageNumber: offset + 1,
			SortBy: 'Id',
			SortType: SortType[SortType.Descending]
		});
		try {
			let action$ = <Observable<SearchRet<Floor>>>this._floorService.Search(criteria.toJS());
			let searchRet: any = await action$.toPromise();
			this.count = searchRet.totalRecords;

			const start = offset * limit;
			const end = start + limit;
			const rows = [...this.rows];

			for (let i = start; i < end; i++) {
				rows[i] = searchRet.items[i - start];
			}

			this.rows = rows;
			this.isPageLoading = false;
			console.log('Page Results', start, end, rows);
		}
		catch (e) {
			if (e.status === 401) {
				this._router.navigate(['/login']);
			}
		}
		finally {

		}
	}


	async delete(id) {
		try {
			await this._dialogService.confirm('确定删除此项目？', '取消', '确认').toPromise();
			await this._floorService.Delete(+id).toPromise();
			await this.ngOnInit();
		}
		catch (e) {
			this._snackBarService.showToast(e.message);
		}
		finally {

		}
	}

	onPage(event) {

		console.log('Page Event', event);
		this.page(event.offset, event.limit);
	}
}
